<?php
/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2015/3/4
 * Time: 14:57
 */

namespace Users\Controller;

/**
 * Class UserController
 * @package Users\Controller
 * 需要在post的时候做额外的检查
 */
class UserController extends BaseUserController
{
    public function __construct()
    {
        parent::__construct();
        $this->_model = $this->_db->users;
        $this->init();
    }

    public function view($id)
    {
        $this->checkAuth();
        parent::view($id);
    }

    public function create()
    {
        if ($this->_data) {
            if (!$this->_data['auth']['username'] || !$this->_data['auth']['password'])
                ClientError('参数错误', C('CODE.BAD_REQUEST')['code']);
            $this->_data = array_merge($this->_data, ['role' => '2']);
            $this->_data['auth']['password'] = md5($this->_data['auth']['password']);
            Success(C('CODE.OK')['code'], $this->_model->create($this->_data));
        } else
            ClientError('参数错误', C('CODE.BAD_REQUEST')['code']);
    }

    public function update($id)
    {
        $this->checkAuth();
        if ($this->_action == 'focus') {
            $labs = $this->_model->find($id);
            if (in_array($this->_data, $labs)) {
                ClientError('重复关注', C('CODE.BAD_REQUEST')['code']);
            } else {
                $this->_model->push($id, $this->_data);
                Success(C('CODE.OK')['code'], $this->_baseModel->find($id));
            }
        } else if ($this->_action == 'cancel') {
            $this->_model->pop($id, $this->_data);
            Success(C('CODE.OK')['code'], $this->_baseModel->find($id));
        } else {
            $this->_model->update($id, $this->_data);
            Success(C('CODE.OK')['code'], $this->_baseModel->find($id));
        }
    }

    public function delete($id)
    {
        parent::delete($id);
    }

    public function checkAuth()
    {
        if ($_REQUEST['userId'] != $this->_token['userId'])
            ClientError('权限不足', C('CODE.UNAUTHORIZED')['code']);
        parent::checkAuth();
    }
}